package com.woyou.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import retrofit.RetrofitError;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.citaq.ideliver.R;
import com.woyou.bean.CodeResult;
import com.woyou.bean.Info;
import com.woyou.bean.Result;
import com.woyou.bean.ShopItem;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.MyShopListReq;
import com.woyou.bean.rpc.ShopCollectReq;
import com.woyou.service.LocationLoopService;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.adapter.MyShopListAdapter;
import com.woyou.ui.api.AdjustListViewHeight;
import com.woyou.ui.component.ErrorHintView;
import com.woyou.ui.component.ErrorHintView.OperateListener;
import com.woyou.ui.component.fastscroll.FastScrollView;
import com.woyou.ui.component.fastscroll.IdleListDetector;
import com.woyou.ui.component.fastscroll.IdleListener;
import com.woyou.utils.Dialog;
import com.woyou.utils.eventbus.EventDeleteShop;

import de.greenrobot.event.EventBus;

/**
 * 我的收藏列表
 * 
 * @author tanglc
 */
@EActivity(R.layout.fm_collection)
public class CollectionActivity extends BaseActivity implements
		AdjustListViewHeight {

	@ViewById(R.id.shop_list)
	ListView shopList; // 店铺收藏列表
	@ViewById
	RelativeLayout myback;// 标题返回按钮
	@ViewById
	TextView head_title, deleteshoptext, lookshop;// 标题内容
	@ViewById
	LinearLayout deleteshop, noshop;

	@ViewById(R.id.loading_iv)
	ImageView loading_iv; // 数据加载

	@ViewById(R.id.load_loading)
	RelativeLayout loading; // 加载效果
	@ViewById(R.id.hintView)
	ErrorHintView mErrorHintView;

	@ViewById
	FastScrollView isscroll;
	private boolean isLocationReady = false;
	private MyShopListReq myShopListReq = new MyShopListReq();
	private List<ShopItem> shopItems = new ArrayList<ShopItem>();// listview数据源
	private List<ShopItem> shopItemsBackUp = new ArrayList<ShopItem>();// listview备份数据源
	private MyShopListAdapter shopAdapter;
	private FastScrollView fastScroller;// 快速滚动器
	private IdleListener idleListener;// 空闲监听器
	private IdleListDetector mPostScrollLoader;// 空闲状态解析器
	// 商品列表

	Dialog dialog = new Dialog();

	protected void setupIdleListener(AbsListView list) {
		idleListener = new IdleListener(list, 0);
		mPostScrollLoader = new IdleListDetector(idleListener);
		fastScroller = (FastScrollView) list.getParent();
		fastScroller.setOnIdleListDetector(mPostScrollLoader);
	}

	double lat;
	double lng;

	@AfterViews
	void afterView() {
		initListView();// 初始化ListView
		MyShopList();
	}

	Result<List<ShopItem>> result = null;

	@Background
	void MyShopList() {
		showViewById(4);
		if (!NetWorkCenter.isNetworkConnected(mActivity)) {
			runOnUI(new Runnable() {
				@Override
				public void run() {
					showViewById(2);
				}
			});
			return;
		}
		UserInfo userInfo = mUserModel.getUserInfo();
		if (userInfo != null && userInfo.getuId() != null) {
			if (mBaiduLocationService.getLastLocation() == null) {
				showViewById(7);
				return;
			}
			try {
				if (LocationLoopService.getInstance(mContext).getChosenAddr() != null) {
					lat = Double.valueOf(LocationLoopService
							.getInstance(mContext).getChosenAddr().getLat());
					lng = Double.valueOf(LocationLoopService
							.getInstance(mContext).getChosenAddr().getLng());
				} else {
					if (mBaiduLocationService.getLastLocation() != null) {
						lat = mBaiduLocationService.getLastLocation()
								.getLatitude();
						lng = mBaiduLocationService.getLastLocation()
								.getLongitude();
					}
				}
				myShopListReq.setuId(userInfo.getuId());
				myShopListReq.setPwd(userInfo.getPwd());
				myShopListReq.setLat(lat + "");
				myShopListReq.setLng(lng + "");
				myShopListReq.setPage(pageNext); // 页号
				result = mUserModel.v2_3myShopList(myShopListReq);
				if (result != null && result.code == 1) {
					runOnUI(new Runnable() {
						public void run() {
							refreshUI(result);
						}
					});
				} else if (result != null && result.code == -3) {
					// 账号挤出
					runOnUI(new Runnable() {
						
						@Override
						public void run() {
							dialog.LoginToast(mContext, result.msg);
							finish();
						}
					});
					
				} else {
					// 无数据返回
					if (result.msg.equals("暂无收藏")) {
						showViewById(5);
					} else {
						showViewById(3);
					}
				}
			} catch (RetrofitError e) {
				switch (e.getKind()) {
				case HTTP:
					showViewById(6);
					return;
				case CONVERSION:
					showViewById(3);
					return;
				case NETWORK:
					showViewById(6);
					return;
				case UNEXPECTED:
					showViewById(3);
					return;
				}
			}
		}
	}

	@Click({ R.id.myback, R.id.deleteshop, R.id.lookshop })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.myback:
			finish();
			break;
			
		case R.id.deleteshop:
			// 刷新列表显示删除按钮
			if (deleteshoptext.getText().toString().equals("编辑")) {
				EventBus.getDefault().post(new EventDeleteShop());
				shopItemsBackUp.clear();
				MyShopListAdapter.sb = new StringBuffer();
				shopItemsBackUp.addAll(shopItems);
				deleteshoptext.setText("完成");
			} else if (deleteshoptext.getText().toString().equals("完成")) {
				if (shopItems.size() == 0) {
					showViewById(5);
				} else {
					deleteshoptext.setText("编辑");
				}

				shopAdapter = new MyShopListAdapter(shopItems, mContext);
				shopList.setAdapter(shopAdapter);
				setupIdleListener(shopList);
				shopCollect();
			}
			break;
		case R.id.lookshop:
			finish();
			break;
		default:
			break;
		}
	}

	private void initListView() {
		head_title.setText("我的收藏");
		deleteshoptext.setText("编辑");
		shopAdapter = new MyShopListAdapter(shopItems, mContext);
		shopList.setAdapter(shopAdapter);
		setupIdleListener(shopList);
	}

	@ItemClick(R.id.shop_list)
	public void shopListItemClick(int position) {
		if (deleteshoptext.getText().toString().equals("编辑")) {
			ShopItem shopItem = shopItems.get(position);
			// 跳转到店铺详情
			Info<ShopItem> info = new Info<ShopItem>(shopItem);
			info.setOrigin(CollectionActivity_.class);
			openActivity(ShopInfoActivity.class, info);
		}
	}

	private void shopCollect() {
		if (!NetWorkCenter.isNetworkConnected(mActivity)) {
			showToast("请检查你的网络!");
			return;
		}
		
		executeTask(new Runnable() {
			
			@Override
			public void run() {
				showProgressDialog();
				try {
					ShopCollectReq shopCollectReq = new ShopCollectReq();
					UserInfo userInfo = mUserModel.getUserInfo();
					shopCollectReq.setuId(userInfo.getuId());
					shopCollectReq.setPwd(userInfo.getPwd());
					if (MyShopListAdapter.sb.toString().length() > 0) {
						shopCollectReq.setsIdList(MyShopListAdapter.sb.toString().split("\\|"));
						shopCollectReq.setIscollect(2);
						CodeResult result = mShopsModel.shopCollect(shopCollectReq);
						shopCollectResult(result);
					}
				} catch (RetrofitError e) {
					showViewById(3);
					switch (e.getKind()) {
					case CONVERSION:
						return;
					case HTTP:
						return;
					case NETWORK:
						return;
					case UNEXPECTED:
						return;
					}
				} finally {
					dismissProgressDialog();
				}
			}
		});
	}

	private void shopCollectResult(final CodeResult result) {
		runOnUI(new Runnable() {
			
			@Override
			public void run() {
				if (result != null && result.code == 1) {
					showToast(result.msg);
					
				} else if (result != null && result.code == -3) {
					dialog.LoginToast(mContext, result.msg);
					finish();
					
				} else if (result != null) {
					showToast(result.msg);
					shopItems.clear();
					shopItems.addAll(shopItemsBackUp);
					shopAdapter = new MyShopListAdapter(shopItems, mContext);
					shopList.setAdapter(shopAdapter);
					setupIdleListener(shopList);
				}
			}
		});
	}

	private int pageNext = 1;

	@UiThread
	void refreshUI(Result<List<ShopItem>> result) {
		dismissProgressDialog();
		List<ShopItem> list = result.getData();
		if (list == null || list.size() == 0) {// 没有数据返回
			showViewById(5);
		} else {
			shopItems.clear();
			pageNext = result.page;
			shopItems.addAll(list);
			shopAdapter.notifyDataSetChanged();
			shopList.setSelection(0);
			showViewById(1);
		}

	}

	@Override
	public boolean backOperate() {
		// TODO Auto-generated method stub
		if (deleteshoptext.getText().toString().equals("编辑")) {
			finish();
			return false;
		} else if (deleteshoptext.getText().toString().equals("完成")) {
			deleteshoptext.setText("编辑");
			shopItems.clear();
			shopItems.addAll(shopItemsBackUp);
			shopAdapter = new MyShopListAdapter(shopItems, mContext);
			shopList.setAdapter(shopAdapter);
			setupIdleListener(shopList);
			showToast("编辑被放弃了");
		}
		return true;
	}

	@Override
	public void adjust(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;

		for (int i = 0; i < listAdapter.getCount(); i++) {
			int height = (int) mContext.getResources().getDimension(
					R.dimen.dp385);
			totalHeight += height;
		}
		totalHeight = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight;
		// ((MarginLayoutParams) params).setMargins(10, 10, 10, 10);
		listView.setLayoutParams(params);

	}

	/**
	 * 显示个人详细信息：1 显示断网：2 显示加载数据失败：3 显示加载中：4 暂无收藏：5 请求超时：6
	 */
	@UiThread
	public void showViewById(int i) {
		hideLoading();
		isscroll.setVisibility(View.GONE);
		loading.setVisibility(View.GONE);
		noshop.setVisibility(View.GONE);
		deleteshop.setVisibility(View.GONE);
		switch (i) {
		case 1:
			stopRotateAnim();
			deleteshop.setVisibility(View.VISIBLE);
			isscroll.setVisibility(View.VISIBLE);
			mErrorHintView.close();
			break;
		case 2:
			stopRotateAnim();
			mErrorHintView.netError(new OperateListener() {

				@Override
				public void operate() {
					startRotateAnim();
					MyShopList();
				}
			});
			break;
		case 3:
			stopRotateAnim();
			mErrorHintView.loadFailure(new OperateListener() {

				@Override
				public void operate() {
					startRotateAnim();
					MyShopList();
				}
			});
			break;
		case 4:
			mErrorHintView.close();
			loading.setVisibility(View.VISIBLE);
			showLoading(loading_iv);
			break;
		case 5:
			deleteshop.setVisibility(View.GONE);
			noshop.setVisibility(View.VISIBLE);
			break;
		case 6:
			stopRotateAnim();
			mErrorHintView.timeOut(new OperateListener() {

				@Override
				public void operate() {
					isLocationReady = false;
					mBaiduLocationService.startLocation();

				}
			});
			break;
		case 7:
			stopRotateAnim();
			mErrorHintView.locationFail(new OperateListener() {

				@Override
				public void operate() {
					startRotateAnim();
					MyShopList();
				}
			});
			break;
		}
	}

	RotateAnimation rotateAnimation;

	@UiThread
	void startRotateAnim() {
		loading.setVisibility(View.VISIBLE);
		// 创建一个RotateAnimation对象（以某个点为圆心旋转360度）
		// 相对于自己的360度旋转
		if (rotateAnimation == null) {
			rotateAnimation = new RotateAnimation(0, 360,
					Animation.RELATIVE_TO_SELF, 0.5f,
					Animation.RELATIVE_TO_SELF, 0.5f);
			rotateAnimation.setDuration(1000);
			rotateAnimation.setRepeatCount(-1); // ndroid:repeatCount
												// 重复的次数，默认为0，必须是int，可以为-1表示不停止
			rotateAnimation.setInterpolator(new LinearInterpolator());
			loading_iv.setAnimation(rotateAnimation);
		}
		// rotateImg.startAnimation(rotateAnimation);
		rotateAnimation.start();
	}

	@UiThread
	void stopRotateAnim() {
		if (rotateAnimation != null) {
			rotateAnimation.cancel();
		}
	}

}
